<template>
  <div>
    <el-table :data="layers" stripe border>
      <el-table-column label="类型" prop="label" width="80px"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showLayer(scope.row)">显示</el-button>
          <el-button type="text" @click="loadLayer(scope.row)">刷新数据</el-button>
          <el-button type="text" @click="clearLayer(scope.row)">清空</el-button>
          <el-button type="text" @click="hideLayer(scope.row)">隐藏</el-button>
        </template>
      </el-table-column>
    </el-table>
    <map-legend v-show="showCustomLayer" :show="showCustomLayer" :options="options" @selectAge="selectAge"></map-legend>
  </div>
</template>

<script>
import mixins from '../mixins';
import MapLegend from './MapLegend';
export default {
  name: 'ThematicTool',
  components: {
    MapLegend
  },
  props: {
    getMap: {
      type: Function,
      required: true
    },
    getTool: {
      type: Function,
      required: true
    },
    mapLoadSuccess: Boolean
  },
  mixins: [mixins],
  data() {
    return {
      layers: [
        {
          value: 'FlashPoint',
          label: '闪烁点',
          random: () => {
            return turf.randomPoint(20, {
              bbox: this.getTool('BaseMapTool').getBounds()
            }).features;
          }
        },
        {
          value: 'ScanPoint',
          label: '扫描点',
          random: () => {
            return turf.randomPoint(20, {
              bbox: this.getTool('BaseMapTool').getBounds()
            }).features;
          }
        },
        {
          value: 'FlowLine',
          label: '流动线',
          random: () => {
            let features = turf.randomLineString(3, {
              bbox: this.getTool('BaseMapTool').getBounds(),
              // eslint-disable-next-line camelcase
              max_length: 0.1
            }).features;
            features.forEach((feature) => {
              feature.properties.width = 4;
              feature.properties.opacity = 1;
            });
            return features;
          }
        },
        {
          value: 'CustomLayer',
          label: '自定义'
        }
      ],
      thematicLayers: {},
      showCustomLayer: false,
      customPrefix: 'Thematic_',
      options: [
        { key: '0', label: '20年以上', range: [20, Infinity], color: 'f58f62' },
        { key: '1', label: '15-20年（不包括第20年）', range: [15, 20], color: 'e5f562' },
        { key: '2', label: '10-15年（不包括第15年）', range: [10, 15], color: '62f573' },
        { key: '3', label: '0-10年（不包括第10年）', range: [0, 10], color: '628ff5' }
      ],
      features: [],
      mapZoom: null
    };
  },
  watch: {},
  methods: {
    showLayer(row) {
      if (!this.thematicLayers[row.value]) {
        if (row.value === 'CustomLayer') {
          // eslint-disable-next-line new-cap
          this.thematicLayers.CustomLayer = this.getTool('ThematicTool').CustomLayer({
            initLayers: this.initLayers,
            refresh: this.refresh
          });
          this.thematicLayers.CustomLayer.events.click = (e) => {
            console.log(e);
          };
          this.loadData();
          this.showCustomLayer = true;
        } else {
          this.thematicLayers[row.value] = this.getTool('ThematicTool')[row.value]();
        }
      }
      this.thematicLayers[row.value].show();
    },
    loadLayer(row) {
      if (this.thematicLayers[row.value]) {
        if (row.value === 'CustomLayer') {
          this.thematicLayers.CustomLayer.setData(turf.featureCollection(this.features));
        } else {
          this.thematicLayers[row.value].setData(turf.featureCollection(row.random()));
        }
      }
    },
    clearLayer(row) {
      if(this.thematicLayers[row.value]) {
        this.thematicLayers[row.value].clear();
      }
    },
    hideLayer(row) {
      if (row.value === 'CustomLayer') {
        this.showCustomLayer = false;
      }
      if(this.thematicLayers[row.value]) {
        this.thematicLayers[row.value].hide();
      }
    },
    loadData() {
      let params = {
        schema: this.option.schema,
        province: '_js',
        ssghrw: this.option.ssghrw,
        ghnf: 2021,
        qyid: 41569
      };
      this.getMap()
        .api.PwghGhsjXzfx.sbfx.post_sbfx_querySbTynxShape({ params: params })
        .then((res) => {
          // eslint-disable-next-line camelcase
          const { resp_code, datas } = res;
          // eslint-disable-next-line camelcase
          if (resp_code === 200) {
            this.getDeviceFeatures(datas);
            this.thematicLayers.CustomLayer.setData(turf.featureCollection(this.features));
          }
        });
    },
    getDeviceFeatures(datas) {
      let features = [];
      let iconSize = this.getIconSize();
      datas.forEach((item) => {
        let tynx = this.getTynxOption(item.tynx);
        let geometry = item.geometry;
        let sblx = this.$MapUtils.SblxUtil.getSblxBySbzlx(item.sbzlx);
        switch (sblx) {
          // 大馈线
          case 100001:
            geometry.forEach((shape) => {
              console.log(shape);
              let line = JSON.parse(shape);
              line.coordinates = this.$MapUtils.CoordinateUtil.projectWebMercatorToLngLat(line.coordinates);
              let lineFeature = turf.feature(line, {
                oid: item.oid,
                sbzlx: item.sbzlx,
                tynxType: tynx.key,
                sourceType: 'LineString',
                color: '#' + tynx.color,
                width: 3,
                opacity: 0.8
              });
              features.push(lineFeature);
            });
            break;
          case 110000:
          case 301000:
          case 302000:
            geometry = JSON.parse(item.geometry);
            geometry.coordinates = this.$MapUtils.GeometryUtil.getCenter(
              this.$MapUtils.CoordinateUtil.projectWebMercatorToLngLat(geometry.coordinates)
            );
            features.push(
              turf.point(geometry.coordinates, {
                oid: item.oid,
                sbzlx: item.sbzlx,
                tynxType: tynx.key,
                sourceType: 'Marker',
                icon: 'zsb-' + tynx.color,
                iconSize: iconSize
              })
            );
            break;
          default:
            console.log(item.sbzlx);
            break;
        }
      });
      this.features = features;
    },
    getTynxOption(tynx) {
      let arr = this.options;
      for (let i = 0; i < arr.length; i++) {
        if (tynx >= arr[i].range[0]) {
          return arr[i];
        }
      }
    },
    getIconSize() {
      let zoom = this.getTool('BaseMapTool').getZoom();
      if (zoom < 13) {
        return 0.5;
      } else if (zoom < 14) {
        return 0.6;
      } else if (zoom < 15) {
        return 0.7;
      } else if (zoom < 15.5) {
        return 0.8;
      } else if (zoom < 16) {
        return 0.9;
      }
      return 1.2;

    },
    initLayers(tool) {
      tool.layeridPrefix = this.customPrefix;
      tool.sourceId = this.customPrefix + 'source_' + tool.id;
      tool.layerIdPrefixes = [];
      tool.layerIds = [];
      if(!tool.getMap().getSource(tool.sourceId)) {
        tool.getMap().addSource(tool.sourceId, {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        });
      }
      this.options.forEach((item) => {
        let layerId = this.customPrefix + item.key;
        tool.layerIdPrefixes.push(layerId);
        tool.layerIds.push(layerId + '_linestring');
        tool.layerIds.push(layerId + '_marker');
        if(!tool.getMap().getLayer(layerId + '_linestring')) {
          tool.getMap().addLayer({
            id: layerId + '_linestring',
            type: 'line',
            source: tool.sourceId,
            filter: ['all', ['==', 'sourceType', 'LineString'], ['==', 'tynxType', item.key]],
            layout: {
              visibility: 'none',
              'line-cap': 'round',
              'line-join': 'round'
            },
            paint: {
              'line-color': ['get', 'color'],
              'line-width': ['get', 'width'],
              'line-opacity': ['get', 'opacity']
            }
          });
        }
        if(!tool.getMap().getLayer(layerId + '_marker')) {
          tool.getMap().addLayer({
            id: layerId + '_marker',
            type: 'symbol',
            source: tool.sourceId,
            filter: ['all', ['==', 'sourceType', 'Marker'], ['==', 'tynxType', item.key]],
            layout: {
              visibility: 'none',
              'icon-image': '{icon}',
              'icon-size': ['get', 'iconSize'],
              'icon-ignore-placement': true,
              'text-ignore-placement': false,
              'text-size': 12,
              'text-allow-overlap': false,
              'icon-anchor': 'center',
              'text-offset': [0, 1],
              'text-font': ['Microsoft YaHei Regular']
            }
          });
        }
      });
    },
    refresh() {
      let zoom = this.getTool('BaseMapTool').getZoom();
      if (!this.mapZoom || zoom.toFixed(1) !== this.mapZoom.toFixed(1)) {
        this.mapZoom = zoom;
        if (this.showCustomLayer) {
          let iconSize = this.getIconSize();
          this.features.forEach((feature) => {
            if (feature.properties.sourceType === 'Marker') {
              feature.properties.iconSize = iconSize;
            }
          });
          this.thematicLayers.CustomLayer.setData(turf.featureCollection(this.features));
        }
      }
    },
    selectAge(selectedAge) {
      let showIds = [];
      let hideIds = [];
      this.options.forEach((item) => {
        let layerId = this.customPrefix + item.key;
        if (selectedAge.indexOf(item.key) > -1) {
          showIds.push(layerId + '_linestring', layerId + '_marker');
        } else {
          hideIds.push(layerId + '_linestring', layerId + '_marker');
        }
      });
      this.thematicLayers.CustomLayer.changeLayerStatusByIds(showIds, 'visible');
      this.thematicLayers.CustomLayer.changeLayerStatusByIds(hideIds, 'none');
    }
  },
  mounted() {}
};
</script>

<style scoped></style>
